package com.westvalley.plugin.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.xml.bind.JAXB;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import com.westvalley.plugin.db.xml.Construct;
import com.westvalley.plugin.db.xml.InvokeFactory;
import com.westvalley.plugin.db.xml.Module;
import com.westvalley.plugin.db.xml.ServicePoint;

public class WeaverMoreDbPlugin implements IPlugin{
	private static final String DB_CONFIG = PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "service" + File.separator + "datasource.xml";

	public boolean start() {
		try {
			Module module = JAXB.unmarshal(new FileReader(new File(DB_CONFIG)), Module.class);
			for(ServicePoint servicePoint : module.servicePoints){
				for(InvokeFactory invokeFactory : servicePoint.invokeFactorys){
					for(Construct construct : invokeFactory.constructs){
						String datasourcename = construct.getDataSourceName();
						IDataSourceProvider dataSourceProvider = new OtherDataSource(construct);
						if( StrKit.notBlank(datasourcename) && dataSourceProvider != null ){
							Config config = new Config(datasourcename, dataSourceProvider.getDataSource(), construct.getDialect());
							DbKit.addConfig(config);
						}
					}
				}
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("Error loading datasource.xml file.", e);
		}
		return true;
	}

	public boolean stop() {
		return true;
	}

}
